package growth

import (
	"clientDemo/service/asynccall"
	"clientDemo/service/cond"
	"clientDemo/service/event"
	"clientDemo/service/modulemgr"
	"clientDemo/utils"
	"fmt"
	"log"
	"time"
)

type GrowthInfo struct {
	Id        uint32
	Level     uint32
	NextLevel uint32
}
type GrowthModule struct {
	condModule  cond.ICondModule
	asyncModule asynccall.IAsyncCallModule
	allData     map[uint32]map[uint32]*GrowthInfo
}

func NewGrowthModule() *GrowthModule {
	tmp := &GrowthModule{
		allData: map[uint32]map[uint32]*GrowthInfo{},
	}
	return tmp
}
func (m *GrowthModule) Init(mm modulemgr.IModuleManager) (bool, error) {
	var ok bool
	m.condModule, ok = mm.GetModule(cond.Name).(cond.ICondModule)
	if !ok {
		return false, fmt.Errorf("failed to assert module to ICondModule")
	}
	m.asyncModule, ok = mm.GetModule(asynccall.Name).(asynccall.IAsyncCallModule)
	if !ok {
		return false, fmt.Errorf("failed to assert module to ICondModule")
	}

	m.condModule.RegeditDataSource(cond.Value_Category_Growth, m.GetRoleGrowthData)
	return true, nil
}

func (m *GrowthModule) Run(mm modulemgr.IModuleManager) (bool, error) {

	var roleId uint32 = 1
	var growthId uint32 = 1
	var level uint64 = 2
	/*	m.allData[1] = map[uint32]*GrowthInfo{
			roleId: {Id: growthId, Level: uint32(level), NextLevel: uint32(level + 1)},
		}
		_ = event.DispatchEvent(
			EventType_Growth_Level_Update,
			&event.EventParams{
				Param: []interface{}{roleId, growthId, level},
			},
		)*/
	m.UpdateLevel(roleId, growthId, level)
	/*	m.condModule.DispatchDataSource(roleId,
		cond.Value_Category_Growth,
		[]interface{}{uint32(growthId), uint32(cond.Cond_ValueParamType_Growth_Level)},
		level)*/
	return false, nil
}

func (m *GrowthModule) UpdateLevel(roleId uint32, growthId uint32, level uint64) {
	m.asyncModule.AsyncDelayTimer(time.Duration(2)*time.Second, func() {
		m.allData[1] = map[uint32]*GrowthInfo{
			roleId: {Id: growthId, Level: uint32(level), NextLevel: uint32(level + 1)},
		}
		level++
		_ = event.DispatchEvent(
			EventType_Growth_Level_Update,
			&event.EventParams{
				Param: []interface{}{roleId, growthId, level},
			},
		)
		//log.Printf("---------------这是定时器协程ID：%v \n", utils.GetGoroutineID())
		m.UpdateLevel(roleId, growthId, level)
		log.Printf("---------------这是定时器协程ID：%v \n", utils.GetGoroutineID())
	})
}
func (m *GrowthModule) GetRoleGrowthData(roleId uint32, param []interface{}) int64 {
	growthData, ok := m.allData[roleId]
	if !ok {
		return 0
	}
	if len(param) < 2 {
		return 0
	}
	dataType, ok := param[1].(uint32)
	if !ok {
		return 0
	}
	if dataType == uint32(cond.Cond_ValueParamType_Growth_Level) {
		growthId, ok := param[0].(uint32)
		if !ok {
			return 0
		}

		data, ok := growthData[growthId]
		if ok {
			return int64(data.Level)
		}
	}
	return 0
}
